//
//  LiveService_Con.swift
//  DaNeng
//
//  Created by fy on 2022/1/13.
//  Copyright © 2022 Mac. All rights reserved.
//

import UIKit
import WebKit
//import CNUIBaseKit

class LiveService_Con: BaseController {
    // &enterurl=%E8%BE%BEe%E8%B4%AD%EF%BC%88ios%EF%BC%89
    // 在 web ⻚面载⼊的对话链接后加上 &appAct=1 参数，开启与 web ⻚面交互
    // 在对话链接中添加参数 &navHidden=1 ，隐藏H5⻚面自带的导航栏。
    var link = "https://care60.live800.com/live800/chatClient/chatbox.jsp?companyID=80028629&configID=3212&enterurl=%E8%BE%BE%E8%83%BD%E6%98%93%E6%8E%8C%E6%9F%9C%EF%BC%88ios%EF%BC%89"
    
    // MARK: Properties
    private lazy var web: WKWebView = {
        var webView = WKWebView()
        // 以下代码适配大小
        let jScript = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta); var imgs = document.getElementsByTagName('img');for (var i in imgs){imgs[i].style.maxWidth='100%';imgs[i].style.height='auto';}"
        let wkUScript = WKUserScript(source: jScript, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        let wkUController = WKUserContentController()
        wkUController.addUserScript(wkUScript)
        let wkWebConfig = WKWebViewConfiguration()
        wkWebConfig.userContentController = wkUController
        webView = WKWebView(frame: CGRect.zero, configuration: wkWebConfig)
        
        webView.backgroundColor = UIColor.white
        return webView
    }()
    
    private lazy var progressView: UIProgressView = UIProgressView()
    
    // MARK: LifeCycle
    override func loadView() {
        super.loadView()
        // AddView
        web.addObserver(self, forKeyPath:"estimatedProgress", options: NSKeyValueObservingOptions.new, context:nil)
        web.navigationDelegate = self
        web.scrollView.delegate = self
        self.view.addSubview(web)
        self.view.addSubview(progressView)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "我的客服"
        
        // Layout
        self.setUI()
        // AddRequest
        self.request_init()
    }
    deinit {
        web.removeObserver(self, forKeyPath:"estimatedProgress")
        web.navigationDelegate = nil
        web.scrollView.delegate = nil
    }
    // MARK: Layout
    private func setUI() {
        web.snp.makeConstraints { (m) in
            m.top.equalToSuperview()
            m.left.right.equalToSuperview()
            if #available(iOS 11.0, *) {
                m.bottom.equalTo(self.view.safeAreaLayoutGuide)
            } else {
                m.bottom.equalToSuperview()
            }
        }
        progressView.snp.makeConstraints { (m) in
            m.left.top.right.equalTo(web)
            m.height.equalTo(1)
        }
        progressView.tintColor = UIColor.init(red: 245/255, green: 77/255, blue: 117/255, alpha: 1)
        progressView.isHidden = true
    }
    
    // MARK: NetWork
    private func request_init() {
        if link == "" {
            
        } else {
            let url = URL(string: self.link)
            let request = URLRequest(url: url!)
            web.load(request)
        }
        
    }
}

extension LiveService_Con: UIScrollViewDelegate {
    
    func scrollViewDidChangeAdjustedContentInset(_ scrollView: UIScrollView) {
        if #available(iOS 11.0, *) {
            self.web.scrollView.contentOffset = CGPoint(x: 0, y: self.web.scrollView.adjustedContentInset.bottom)
        }
    }
}

// MARK: - WKNavigationDelegate
extension LiveService_Con: WKNavigationDelegate {
    override func observeValue(forKeyPath keyPath:String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        // 加载进度
        if keyPath == "estimatedProgress" {
            let newprogress = change?[.newKey]!as! Double
            let oldprogress = change?[.oldKey]as? Double ?? 0.0
            
            //不要让进度条倒着走...有时候goback会出现这种情况
            if newprogress < oldprogress {
                return
            }
            if newprogress == 1 {
                progressView.isHidden = true
                progressView.setProgress(0, animated:false)
            } else {
                progressView.isHidden = false
                progressView.setProgress(Float(newprogress), animated:true)
            }
        }
        
    }
    
    func webView(_ webView:WKWebView, didFinish navigation: WKNavigation!) {
        progressView.isHidden = true
        progressView.setProgress(0, animated:false)
        
    }
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let url = navigationAction.request.url?.absoluteString
        guard let urlStr = url else {
            decisionHandler(WKNavigationActionPolicy.cancel)
            return
        }
        // Live800 定义的交互协议头
        let htmlHeadString = "live800cmd://"
        
        // 拦截 WebView 跳转 通过自⼰的方式处理
        if urlStr.hasPrefix(htmlHeadString) {
            
            //实现与 web 页⾯的交互，详细内容参考Demo
            self.javasriptEvent(url: urlStr)
            
            // 拦截跳转需要取消 webView 中的跳转
            decisionHandler(WKNavigationActionPolicy.cancel)
        } else {
            // 如果是跳转一个新页面（a标签）
            if navigationAction.targetFrame == nil {
                // 创建一个新页面并显示
                let con = LiveService_Con()
                self.cn_pushController(controller: con, hideNavigationBar: false, statusBarDarkMode: false)
                
                // 拦截跳转需要取消 webView 中的跳转
                decisionHandler(WKNavigationActionPolicy.cancel)
                return
            }
            // 走webView默认跳转
            decisionHandler(WKNavigationActionPolicy.allow)
        }
        
    }
    func webView(_ webView:WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        progressView.isHidden = true
        progressView.setProgress(0, animated:false)
        
    }
    
    // MARK: Javascript事件处理
    private func javasriptEvent(url: String) {
        let components = NSURLComponents(string: url)
        let item = components?.queryItems?[0] as NSURLQueryItem?
        
        let paramsValue = item?.value
        
        if url.contains("changeChatStatus") {
            // 访客对话状态改变回调
            // 参数名params，参数状态 W:对话正在等待接通，C:对话已接通，E：对话已结束
            if paramsValue == "W" {
                
            } else if paramsValue == "C" {
                
            } else if paramsValue == "E" {
                
            }
            
        } else if url.contains("newMsg") {
            // 客服新消息状态，目前只会传空字符串或者null
            
        } else if url.contains("closeChat") {
            // 关闭对话操作
            // 参数名params，参数状态 1:访客主动关闭对话，2:长时间未回复关闭对话，3：客服关闭对话
            if paramsValue == "1" {
                
            } else if paramsValue == "2" {
                
            } else if paramsValue == "3" {
                
            }
            
        } else if url.contains("changeEvalStatus") {
            // 访客对话评估状态
            // 参数名params，参数状态 0：已取消评估，1：已评估
            if paramsValue == "0" {
                
            } else if paramsValue == "1" {
                
            }
            
        } else if url.contains("backPage") {
            // 对话结束评估（或取消）后的操作
            // 参数名params，参数状态 1：返回对话界面，2：返回发起对话的页面
            if paramsValue == "1" {
                
            } else if paramsValue == "2" {
                
            }
        }
    }
    
}

